package com.tinem.platform.module.starter.sdk.core;

import com.tinem.platform.module.starter.sdk.config.OAuth2Config;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className TokenManager
 * @description TODO
 * @site 
 * @company 
 * @create 2020-09-04 15:04
 */
@Slf4j
public class TokenManager {
    Lock lock = new ReentrantLock();
    String accessToken;
    Long expires;
    @Resource
    OAuth2Config oAuth2Config;

    public String getAccessToken(){
        if(expires != null && expires > System.currentTimeMillis() ){
            return accessToken;
        }
        lock.lock();
        try {
            if(expires != null && expires > System.currentTimeMillis() ){
                return accessToken;
            }
            String body = HttpUtil.get(StrUtil.format(oAuth2Config.getOauthTokenUrl(),oAuth2Config.getClientId(),oAuth2Config.getClientSecret()));
            log.debug(body);
            JSONObject token = JSONObject.parseObject(body);
            accessToken = token.getString("access_token");
            expires = System.currentTimeMillis()-60+token.getLong("expires_in")*1000;
            return accessToken;
        }finally {
            lock.unlock();
        }
    }

}
